package com.cictec.middleware.tde.rm.disp.receiver.handler;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.Result;
import com.cictec.middleware.commons.utils.ResultUtil;
import com.cictec.middleware.core.entity.Device;
import com.cictec.middleware.core.pojo.MiddlewareDriverSign;
import com.cictec.middleware.feign.distribute.MiddlewareDeviceService;
import com.cictec.middleware.feign.distribute.MiddlewareDriverService;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x24TerminalMessage;

/**
 * 刷卡上报（司机签到），接收指令应答确认
 * 
 * @author Administrator
 *
 */
@Component
@HandleMessages(0X24)
public class TerminalRFIDHandler extends AbstractReceiverHandler {

	private static Logger logger = LoggerFactory.getLogger(TerminalRFIDHandler.class);

	@Autowired
	private MiddlewareDriverService middlewareDriverService;
	@Autowired
	private MiddlewareDeviceService middlewareDeviceService;

	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {
		Rm0x24TerminalMessage msg = (Rm0x24TerminalMessage) message;

		sendMessageToTerminal(createResponse(message), session);

		logger.info("【0X24 刷卡上报（司机签到）】终端 {} Session {} 司机刷卡卡号 {} ", msg.getTerminalId(), message.getSessionId(),
				msg.getCardNumber());

		doDriverCheckIn(msg, session);
	}

	/**
	 * 处理司机签到。
	 * 
	 * @param msg
	 */
	private void doDriverCheckIn(Rm0x24TerminalMessage msg, IoSession session) {

		String devCode = msg.getTerminalId();

		Device device = middlewareDeviceService.getDeviceByDevCode(devCode);
		MiddlewareDriverSign driverSign = new MiddlewareDriverSign(device.getCityCode(), devCode, msg.getCardNumber(), msg.getCreateTime());
		Result result = middlewareDriverService.driverSign(driverSign);

		String content = null;
		if (ResultUtil.isSuccess(result)) {
			Map data = (Map) result.getData();
			String driverName = PMSUtils.isNull(data.get("drvName"));
			content = MessageFormat.format(" {0} 签到成功，祝您工作开心。", driverName);
		} else {
			content = "无法识别的IC卡";
			logger.warn("司机签到处理，查询不到该司机：cardNumber：" + msg.getCardNumber());
		}

		sendMessageToTerminal(createDriverSignResponseMessage(msg.getHeader().getLineId(), Long.parseLong(devCode), content), session);

	}

}
